package com.qf.pojo;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;

import java.io.InputStream;

@ComponentScan("com.qf.pojo") //扫描指定包下交给spring容器管理的类
@Configuration //配置当前类为核心入口类
public class SpringConfiguration {
    @Bean //该注解表示此方法提供一个对象到spring工厂进行管理
    public SqlSessionFactory getFactory(){
        //SqlSessionFactory会话工厂对象需要单例
        SqlSessionFactory sessionFactory =null;
        try {
            InputStream inputStream = Resources.getResourceAsStream("SqlMapConfig.xml");
            sessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return sessionFactory;
    }
    @Bean //该注解修饰的方法的参数会由spring自动注入
    @Scope("prototype") //spring默认是单例的，这里需要使用@Scope将该方法设置为多例
    public SqlSession getSqlSession(SqlSessionFactory sessionFactory){
        //SqlSession会话对象需要多例
        SqlSession sqlSession = sessionFactory.openSession();
        return sqlSession;
    }
}
